<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules" v-bind="layout">
        <!-- 基本信息 -->
        <a-card title="基本信息" size="small" style="margin-bottom: 16px">
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-model-item label="模板编码" prop="templateCode">
                <a-input v-model="model.templateCode" placeholder="请输入模板编码"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="模板名称" prop="templateName">
                <a-input v-model="model.templateName" placeholder="请输入模板名称"></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-model-item label="是否默认" prop="isDefault">
                <a-switch
                  :checked="model.isDefault === 1"
                  @change="handleDefaultChange"
                  checked-children="是"
                  un-checked-children="否"
                ></a-switch>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="状态" prop="status">
                <j-dict-select-tag
                  v-model="model.status"
                  dictCode="valid_status"
                  placeholder="请选择状态"
                ></j-dict-select-tag>
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item label="模板描述" prop="description">
                <a-textarea v-model="model.description" placeholder="请输入模板描述" :rows="3"></a-textarea>
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item label="备注" prop="remark">
                <a-textarea v-model="model.remark" placeholder="请输入备注" :rows="2"></a-textarea>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>

        <!-- 工种配置 -->
        <a-card title="工种配置" size="small">
          <template slot="extra">
            <a-button type="primary" size="small" @click="handleAddWorkType" icon="plus"> 添加工种 </a-button>
          </template>

          <a-table
            :columns="workTypeColumns"
            :dataSource="model.workTypes"
            :pagination="false"
            rowKey="key"
            size="small"
            bordered
          >
            <template slot="workTypeName" slot-scope="text, record, index">
              <a-select
                v-model="record.workTypeId"
                @change="(value) => handleWorkTypeChange(value, index)"
                placeholder="请选择工种"
                showSearch
                style="width: 100%"
              >
                <a-select-option v-for="workType in workTypeOptions" :key="workType.id" :value="workType.id">
                  {{ workType.workTypeName }}
                </a-select-option>
              </a-select>
            </template>

            <template slot="sequence" slot-scope="text, record">
              <a-input-number v-model="record.sequence" :min="1" :max="999" placeholder="顺序" style="width: 100%">
              </a-input-number>
            </template>

            <template slot="isRequired" slot-scope="text, record, index">
              <a-switch
                :checked="record.isRequired === 1"
                @change="(value) => handleRequiredChange(value, record, index)"
              ></a-switch>
            </template>

            <template slot="remark" slot-scope="text, record">
              <a-input v-model="record.remark" placeholder="备注"></a-input>
            </template>

            <template slot="action" slot-scope="text, record, index">
              <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteWorkType(index)">
                <a style="color: red">删除</a>
              </a-popconfirm>
            </template>
          </a-table>
        </a-card>
      </a-form-model>
    </a-spin>
  </j-modal>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'

export default {
  name: 'TemplateForm',
  components: {},
  data() {
    return {
      title: '操作',
      width: 800,
      visible: false,
      model: {
        workTypes: [],
      },
      confirmLoading: false,
      layout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 },
      },
      validatorRules: {
        templateCode: [{ required: true, message: '请输入模板编码!' }, { validator: this.validateTemplateCode }],
        templateName: [{ required: true, message: '请输入模板名称!' }],
        status: [{ required: true, message: '请选择状态!' }],
      },
      url: {
        add: '/mes/template/add',
        edit: '/mes/template/edit',
        saveWithWorkTypes: '/mes/template/saveWithWorkTypes',
        queryById: '/mes/template/queryById',
        getWorkTypes: '/mes/worktype/list',
      },
      workTypeOptions: [],
      workTypeColumns: [
        {
          title: '工种',
          dataIndex: 'workTypeName',
          width: 200,
          scopedSlots: { customRender: 'workTypeName' },
        },
        {
          title: '工序顺序',
          dataIndex: 'sequence',
          width: 100,
          scopedSlots: { customRender: 'sequence' },
        },
        {
          title: '是否必需',
          dataIndex: 'isRequired',
          width: 100,
          scopedSlots: { customRender: 'isRequired' },
        },
        {
          title: '备注',
          dataIndex: 'remark',
          scopedSlots: { customRender: 'remark' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 80,
          scopedSlots: { customRender: 'action' },
        },
      ],
    }
  },
  created() {
    this.loadWorkTypes()
  },
  methods: {
    add() {
      this.edit({})
    },
    edit(record) {
      this.visible = true

      if (record.id) {
        // 编辑时加载详细信息
        this.loadTemplateDetail(record.id)
      } else {
        // 新增时设置默认值
        this.model = {
          templateCode: '',
          templateName: '',
          status: 1,
          isDefault: 0,
          remark: '',
          workTypes: [],
        }
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.resetForm()
    },
    handleOk() {
      console.log('handleOk 被调用')
      console.log('表单数据:', this.model)
      console.log('表单引用:', this.$refs.form)

      this.confirmLoading = true
      let httpurl = this.url.saveWithWorkTypes

      console.log('准备调用API:', httpurl, this.model)

      postAction(httpurl, this.model)
        .then((res) => {
          console.log('API响应:', res)
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .catch((error) => {
          console.error('API调用失败:', error)
          this.$message.error('保存失败：' + error.message)
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    handleCancel() {
      this.close()
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.model = {
        workTypes: [],
      }
    },
    validateTemplateCode(rule, value, callback) {
      if (!value) {
        callback()
        return
      }

      let params = {
        tableName: 'mes_production_template',
        fieldName: 'template_code',
        fieldVal: value,
        dataId: this.model.id,
      }
      validateDuplicateValue(params).then((res) => {
        if (res.success) {
          callback()
        } else {
          callback(res.message)
        }
      })
    },
    loadWorkTypes() {
      getAction(this.url.getWorkTypes, { pageSize: 999 }).then((res) => {
        if (res.success) {
          this.workTypeOptions = res.result.records || []
        }
      })
    },
    loadTemplateDetail(id) {
      getAction(`/mes/template/detail/${id}`).then((res) => {
        if (res.success && res.result) {
          this.model = Object.assign({}, res.result.template)
          this.model.workTypes = res.result.workTypes || []

          // 为每个工种配置添加key
          this.model.workTypes.forEach((item, index) => {
            this.$set(item, 'key', index)
          })
        }
      })
    },
    handleAddWorkType() {
      console.log('handleAddWorkType called')
      console.log('Current model:', this.model)
      console.log('Current workTypes:', this.model && this.model.workTypes)

      // 确保 model 和 workTypes 已初始化
      if (!this.model) {
        this.model = {}
      }
      if (!this.model.workTypes) {
        this.$set(this.model, 'workTypes', [])
      }

      // 创建新的工种行，提供空白选项供用户选择
      const newWorkType = {
        key: Date.now(), // 使用时间戳作为唯一key
        workTypeId: '', // 工种ID - 用户需要从下拉框选择
        workTypeCode: '', // 工种编码 - 选择工种后自动填充
        workTypeName: '', // 工种名称 - 选择工种后自动填充
        sequence: this.model.workTypes.length + 1, // 自动设置序号
        isRequired: 0, // 默认非必需
        remark: '', // 备注为空
      }

      console.log('New work type to add:', newWorkType)

      // 使用Vue响应式方法添加新工种行
      const currentWorkTypes = [...this.model.workTypes]
      currentWorkTypes.push(newWorkType)
      this.$set(this.model, 'workTypes', currentWorkTypes)

      console.log('Updated workTypes:', this.model.workTypes)

      // 触发视图更新，确保表格显示新行
      this.$nextTick(() => {
        console.log('Force update triggered')
        this.$forceUpdate()
      })
    },
    handleDeleteWorkType(index) {
      this.model.workTypes.splice(index, 1)
      // 重新排序
      this.model.workTypes.forEach((item, idx) => {
        item.sequence = idx + 1
      })
    },
    handleWorkTypeChange(value, index) {
      console.log('handleWorkTypeChange called:', value, index)
      const selectedWorkType = this.workTypeOptions.find((item) => item.id === value)
      console.log('Selected work type:', selectedWorkType)

      if (selectedWorkType) {
        // 创建新的工种对象，确保Vue能检测到变化
        const updatedWorkType = {
          ...this.model.workTypes[index],
          workTypeId: value,
          workTypeCode: selectedWorkType.workTypeCode,
          workTypeName: selectedWorkType.workTypeName,
        }
        // 替换整个数组以确保响应式更新
        const newWorkTypes = [...this.model.workTypes]
        newWorkTypes[index] = updatedWorkType
        this.$set(this.model, 'workTypes', newWorkTypes)

        console.log('Updated work type at index', index, ':', updatedWorkType)

        // 使用nextTick确保DOM更新完成
        this.$nextTick(() => {
          this.$forceUpdate()
        })
      }
    },
    handleDefaultChange(value) {
      console.log('默认状态切换:', value)
      this.model.isDefault = value ? 1 : 0
    },
    handleRequiredChange(value, record, index) {
      console.log('handleRequiredChange called:', value, record, index)

      // 使用数组替换方式确保Vue响应式更新
      const newWorkTypes = [...this.model.workTypes]
      newWorkTypes[index] = {
        ...newWorkTypes[index],
        isRequired: value ? 1 : 0,
      }
      this.$set(this.model, 'workTypes', newWorkTypes)

      console.log('Updated isRequired for index', index, ':', newWorkTypes[index].isRequired)

      // 使用nextTick确保DOM更新完成
      this.$nextTick(() => {
        this.$forceUpdate()
      })
    },
  },
}
</script>

<style lang="less" scoped>
</style>
